<template>
  <div class="container">
    <uv-navbar title="发布动态" leftIcon="close" @leftClick="closeFunc" :placeholder="true"></uv-navbar>

    <uv-textarea border="none" v-model="params.textContent" placeholder="记录生活，展示真实的你" maxlength="-1" autoHeight :customStyle="textStyle"></uv-textarea>

    <view class="main">
      <view class="voice" v-if="params.recordingUrl">
        <customAudio :audioSrc="params.recordingUrl"></customAudio>
      </view>
      <view class="imgs" v-show="params.multipartFile.length">
        <uploader ref="uploaderCom" valType="arr" size="104" background="#D8D8D8" v-model="params.multipartFile" :maxCount="9"></uploader>
      </view>
      <view class="address" v-if="params.address&&params.longitude&&params.latitude">
        <view class="flex alignCenter">
          <uv-icon name="map-fill" color='#9E06FF' size="18"></uv-icon>
          <text class="fz12">{{ params.address }}</text>
        </view>
      </view>
    </view>

    <view class="footer">
      <view class="topics flex alignCenter">
        <view v-if="selectTopic.id" class="topic active">
          <view class="flex fz12" style="align-items:inherit">
            <uv-image src="https://qn.taozapp.cn/%E8%AF%9D%E9%A2%98%401.5x.png" radius="50%" width="16px" height="16px"></uv-image>
            <view class="text" @click="current=null">{{selectTopic.topicName}}</view>
            <uv-icon name="close" size="12" color="#B141FF" @click="selectTopic={}"></uv-icon>
          </view>
        </view>

        <view v-else class="topic shrink" @click="instance.refs.popup.open('bottom')">
          <view class="flex alignCenter fz12 shrink">
            <uv-image src="https://qn.taozapp.cn/%E8%AF%9D%E9%A2%98%401.5x.png" radius="50%" width="16px" height="16px"></uv-image>
            <view class="text flex alignCenter">添加话题
              <uv-icon name="arrow-right" size="11" color="#0A0A0A"></uv-icon>
            </view>
          </view>
        </view>

        <view class="topicList flex" v-if="!selectTopic.id">
          <view class="shrink aBox" :class="{active:current===index}" v-for="(item,index) in topicList" :key="index" @click="topicClick(item,index)">
            <view class="flex alignCenter fz12">
              <uv-image src="https://qn.taozapp.cn/%E8%AF%9D%E9%A2%98%401.5x.png" radius="50%" width="16px" height="16px"></uv-image>
              <view class="text">{{item.topicName}}</view>
            </view>
          </view>
        </view>
      </view>
      <view class="actionBtn flex alignCenter justifyBetween">
        <view class="flex alignCenter">
          <uv-image @click="handleClick(1)" :customStyle="iconStyle" src="https://qn.taozapp.cn/%E7%85%A7%E7%89%87%403x.png" width="25px" height="25px"></uv-image>
          <uv-image @click="handleClick(2)" :customStyle="iconStyle" src="https://qn.taozapp.cn/%E8%AF%AD%E9%9F%B3%403x.png" width="25px" height="25px"></uv-image>
          <uv-image @click="instance.refs.selectFriendsCom.open()" :customStyle="iconStyle" src="https://qn.taozapp.cn/%E8%89%BE%E7%89%B9%403x.png" width="25px" height="25px"></uv-image>
          <uv-image :customStyle="iconStyle" @click="selectAddress" src="https://qn.taozapp.cn/%E4%BD%8D%E7%BD%AE%403x.png" width="25px" height="25px"></uv-image>
        </view>
        <uv-button text="发 布" :loading="loading" color="#CF83FF" shape="circle" :customStyle="releaseStyle" @click="save"></uv-button>
      </view>
    </view>
    <tapeAudio ref="tapeAudioCom" v-model="params.recordingUrl"></tapeAudio>

    <uv-popup ref="popup" round="15">
      <view class="popup-content">
        <view class="top flex justifyBetween alignCenter">
          <text @click="instance.refs.popup.close()">取消</text>
          <text class="defaultTopic" @click="defaultTopic">默认话题</text>
        </view>
        <scroll-view :scroll-y="true" class="topList" @scrolltolower="scrolltolower">
          <view class="box flex" v-for="(item,index) in topicList" :key="index" @click="topicSelect(item.id,index)">
            <view class="left">
              <image :src="item.topicImage" mode="widthFix" />
            </view>
            <view class="info">
              <view class="fz14">{{item.topicName}}</view>
              <view class="fz12 desc">{{item.NumberOfParticipants}}人参与</view>
            </view>
          </view>
        </scroll-view>
      </view>
    </uv-popup>

    <selectFriends ref="selectFriendsCom" v-model="params.friendId"></selectFriends>
  </div>
</template>

<script setup lang="ts">
import selectFriends from "@/packagePages/dynamic/components/selectFriends.vue";
import customAudio from "@/components/uv/customAudio.vue";
import tapeAudio from "@/components/uv/tapeAudio.vue"; //录音
import uploader from "@/components/uv/uploader.vue";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();

let loading = ref(false);
let current = ref(null);
let params = ref({
  address: "",
  textContent: "",
  location: "",
  longitude: "",
  latitude: "",
  multipartFile: [],
  topicId: "",
  friendId: [], //@
  recordingUrl: "", //https://qn.taozapp.cn/FiMi_hEKyu7VOTZRINE0sLBGxmCc
});
let imgs = ref([]);
let page = {
  page: 1,
  pageSize: 100,
};
let totalPages = 0;
let textStyle = ref({
  minHeight: "200px",
});
let iconStyle = ref({
  marginRight: "15px",
});
let releaseStyle = ref({
  height: "32px",
});
let topicList = ref([]);
let selectTopic = ref({}); //选中的话题

onLoad(() => {
  getTopic();
});

onShow(() => {
  let slParams = uni.getStorageSync("slParams");
  if (
    slParams.hasOwnProperty("dynamicParams") &&
    !proxy.$utils.isEmptyObject(slParams.dynamicParams)
  ) {
    params.value = slParams.dynamicParams;
    counter.setRelease("dynamicParams", {});
  }
});

function handleClick(index) {
  switch (index) {
    case 1:
      instance.refs.uploaderCom.exampleUploadFn();
      break;
    case 2:
      instance.refs.tapeAudioCom.open();
      break;
    default:
      break;
  }
}

//获取话题
async function getTopic() {
  let resp = await proxy.$apis.queryAllTopic(page);
  let arr = [...topicList.value];
  if (resp.records.length) {
    arr = proxy.$utils.filterArr(arr, resp.records, "id");
  }
  topicList.value = arr;
  totalPages = resp.totalPages;
  console.log("话题", topicList.value);
}

//默认话题
async function defaultTopic() {
  let resp = await proxy.$apis.getDefaultTopic();
  params.value.topicId = resp.id;
  selectTopic.value = resp;
  instance.refs.popup.close();
}

async function selectAddress() {
  let res = await proxy.$auth.chooseLocation();
  params.value.address = res.address;
  params.value.longitude = res.longitude;
  params.value.latitude = res.latitude;
}

function topicClick(item, index) {
  current.value = index;
  params.value.topicId = item.id;
  selectTopic.value = item;
}

function scrolltolower() {
  if (page.page >= totalPages) return;
  page.page++;
  getTopic();
}

function topicSelect(e, index) {
  params.value.topicId = e;
  current.value = index;
  instance.refs.popup.close();
  selectTopic.value = topicList.value[index];
}

async function save() {
  try {
    loading.value = true;
    await proxy.$apis.publishuUpdates(params.value);
    proxy.$utils.showToast("发布成功");
    proxy.$utils.toLink("/pages/tabbar/tabbar-2/tabbar-2", "tab");
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function closeFunc() {
  let flag = false;
  let form = { ...params.value };
  for (let key in form) {
    if (proxy.$utils.isArray(form[key])) {
      if (form[key].length) {
        console.log("form[key]1111", key, form[key].length);
        flag = true;
      }
    } else if (form[key]) {
      console.log("form[key]2222", key);
      flag = true;
    }
  }
  //如果里面的对象有值，则存为草稿
  if (flag) {
    let resp = await proxy.$utils.showModal({
      title: "存为草稿",
      content: "将此次编辑内容保留?",
      cancelText: "不保留",
      confirmText: "保留",
      confirmColor: "#6B68F3",
      cancelColor: "#0E0E0E",
    });
    if (resp) counter.setRelease("dynamicParams", params.value);
  }
  proxy.$utils.toLink("/pages/tabbar/tabbar-2/tabbar-2", "tab");
}

watch(
  () => params.value.friendId,
  (newValue, oldValue) => {
    if (newValue && newValue.length) {
      let obj = newValue[newValue.length - 1];
      params.value.textContent = params.value.textContent + " @" + obj.nikeName;
    }
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
.container {
  padding: 0 0 100px;
  background: white;
  .main {
    padding: 15px;
    .voice {
      margin-bottom: 15px;
    }
    .address {
      background-color: #f0f0f0;
      border-radius: 16px;
      margin-top: 10px;
      padding: 7px 10px;
      display: inline-block;
      text {
        margin-left: 3px;
        color: #999999;
      }
    }
  }
  .footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: white;
    .topics {
      padding-left: 15px;
      margin-bottom: 10px;
      .active {
        background: #f2d6ff !important;
        color: #9e06ff;
      }
      .topicList {
        overflow: auto;
        .aBox {
          margin-right: 6px;
        }
      }
      .topic {
        background: #f2f2f2;
        border-radius: 12px;
        display: inline-block;
        padding: 3px 7px;
        margin-right: 6px;
        white-space: nowrap;
        .text {
          margin: 0 5px;
        }
      }
    }
    .actionBtn {
      border-top: 1px solid #ebebeb;
      padding: 15px 15px 25px 15px;
    }
  }
  .popup-content {
    padding: 25px 15px;
    .top {
      color: #999999;
      font-size: 16px;
      .defaultTopic {
        color: #9e06ff !important;
      }
    }
    .topList {
      max-height: 60vh;
      .box {
        margin-top: 10px;
        .left {
          width: 100px;

          image {
            display: block;
            border-radius: 5px;
          }
        }
        .info {
          margin-left: 10px;
          .desc {
            color: #999999;
            margin-top: 5px;
          }
        }
      }
    }
  }
}
</style>

